import minimist from 'minimist';

import * as fs from 'fs';
import ejs from 'ejs';
import path from 'path';

import toml from '@iarna/toml';

// 替换 &lt; 和 &gt;
function replaceHtmlEntities(content) {
    return content.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}
function renderAndWrite(templatePath, outputPath, data, options) {
    const templateContent = fs.readFileSync(templatePath, 'utf8');
    const renderedContent = ejs.render(templateContent, data, options);
    const formattedContent = replaceHtmlEntities(renderedContent);
    fs.writeFileSync(outputPath, formattedContent);
}

export function generateTomlAPIFiles(argv_minimist) {
    console.log('generateTomlAPIFiles:', argv_minimist);

    const filePaths = {
        controller: "./utils/build/controller.rs",
        service: "./utils/build/service.rs",
        model: "./utils/build/model.rs",
        router: "./utils/build/router.rs"
    };

    const tomlContent = fs.readFileSync('./utils/api.toml', 'utf-8');
    const parsedData = toml.parse(tomlContent);
    console.log(JSON.stringify(parsedData));

    const options = { open: '{{', close: '}}' };
    const data = {
        data: parsedData,
        capitalizeFirstLetter: capitalizeFirstLetter,
    };

    renderAndWrite("./utils/template/controller.ejs", filePaths.controller, data, options);
    renderAndWrite("./utils/template/service.ejs", filePaths.service, data, options);
    renderAndWrite("./utils/template/model.ejs", filePaths.model, data, options);
    renderAndWrite("./utils/template/router.ejs", filePaths.router, data, options);
}

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
